<template>
  <view class="chat-container">
    <ChatSSEClient
      ref="chatSSEClientRef"
      @onMessage="messageCore"
      @onFinish="finishCore"
    ></ChatSSEClient>
    <!-- 头部栏 -->
    <view class="header">
      <!-- <div>nihao</div> -->
      <view class="back-btn" @tap="goBack">
        <up-icon name="arrow-left" color="#333" size="20"></up-icon>
      </view>
      <view class="header-content">
        <image
          class="header-avatar"
          :src="aiObject.avatar"
          mode="aspectFill"
        ></image>
        <text class="header-title">{{ aiObject.name }}</text>
      </view>
      <view class="export-btn" @tap="exportChatHistory">
        <up-icon name="download" color="#333" size="20"></up-icon>
      </view>
    </view>

    <!-- 聊天记录区域 -->
    <scroll-view class="chat-list" scroll-y="true" :scroll-top="scrollTop">
      <view
        v-for="(item, index) in chatList"
        :key="index"
        class="chat-item"
        :class="item.type === 'user' ? 'chat-right' : 'chat-left'"
      >
        <image
          v-if="item.type === 'ai'"
          class="avatar"
          :src="aiObject.avatar"
          mode="aspectFill"
        ></image>
        <view class="message-content">
          <!-- 深度思考内容 -->
          <view
            v-if="item.type === 'ai' && item.reasoningContent"
            class="reasoning-bubble"
          >
            <view class="reasoning-header">
              <up-icon
                name="question-circle"
                color="#1989fa"
                size="16"
              ></up-icon>
              <text class="reasoning-title">深度思考</text>
            </view>
            <text>{{
              item.isStreaming
                ? item.streamReasoningContent
                : item.reasoningContent
            }}</text>
          </view>
          <!-- 回答内容 -->
          <view
            class="chat-bubble"
            :class="item.type === 'user' ? 'user-bubble' : 'ai-bubble'"
          >
            <text v-if="item.type === 'user'">{{ item.content }}</text>
            <text v-else>{{
              item.isStreaming ? item.streamContent : item.content
            }}</text>
            <text v-if="item.isStreaming" class="typing-cursor">|</text>
          </view>
        </view>
        <image
          v-if="item.type === 'user'"
          class="avatar"
          :src="userAvatar"
          mode="aspectFill"
        ></image>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="input-area">
      <input
        type="text"
        v-model="inputMessage"
        class="message-input"
        placeholder="请输入消息..."
        @confirm="sendMessage"
      />
      <button class="send-btn" @tap="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
// import { marked } from "marked";
import ChatSSEClient from "@/components/gao-ChatSSEClient/gao-ChatSSEClient.vue";
const userAvatar = ref("/static/img/chatDetail/user-avatar.jpg");
const aiObject = ref();
const API_KEY = ref(
  "Bearer sk-wuzufxjhrsseyridmvhcjxcasxubhpaqidepmabsdobmpgba"
);
const API_URL = ref("https://api.siliconflow.cn/v1/chat/completions");
const chatId = ref(""); // 用于存储聊天ID
const chatSSEClientRef = ref(null);
onLoad((option) => {
  aiObject.value = option;
  // console.log("aiObject", aiObject.value);

  // 使用AI ID作为唯一标识符，不再使用时间戳
  chatId.value = `chat_${aiObject.value.id || "default"}`;

  // 加载本地存储的聊天记录
  loadChatHistory();
});

onUnload(() => {
  chatSSEClientRef.value.stopChat();
  console.log("卸载");
});

// 聊天记录
const chatList = ref([]);

// 监听聊天记录变化，保存到本地
watch(
  chatList,
  (newVal) => {
    if (newVal.length > 0) {
      saveChatHistory();
    }
  },
  {
    deep: true,
  }
);

// 加载聊天历史记录
const loadChatHistory = () => {
  try {
    // 尝试从本地存储加载聊天记录
    uni.getStorage({
      key: chatId.value,
      success: (res) => {
        if (res.data && Array.isArray(res.data)) {
          chatList.value = res.data;
          console.log("已加载聊天记录", chatList.value.length);
          nextTick(() => {
            scrollToBottom();
          });
        }
      },
      fail: (err) => {
        console.log("没有找到聊天记录或加载失败", err);
        // 初始化空的聊天记录
        chatList.value = [];
      },
    });
  } catch (error) {
    console.error("加载聊天记录错误:", error);
  }
};

// 保存聊天历史记录
const saveChatHistory = () => {
  try {
    // 保存聊天记录到本地存储
    uni.setStorage({
      key: chatId.value,
      data: chatList.value,
      success: () => {
        console.log("聊天记录已保存");
      },
      fail: (err) => {
        console.error("保存聊天记录失败:", err);
      },
    });
  } catch (error) {
    console.error("保存聊天记录错误:", error);
  }
};

// 导出聊天记录为文本文件
const exportChatHistory = () => {
  try {
    // 格式化聊天记录为文本
    let chatText = `聊天记录 - ${aiObject.value.name}\n`;
    chatText += `导出时间: ${new Date().toLocaleString()}\n\n`;

    chatList.value.forEach((msg, index) => {
      const time = new Date().toLocaleTimeString();
      if (msg.type === "user") {
        chatText += `[用户] ${time}\n${msg.content}\n\n`;
      } else {
        chatText += `[${aiObject.value.name}] ${time}\n${msg.content}\n\n`;
        if (msg.reasoningContent) {
          chatText += `[深度思考]\n${msg.reasoningContent}\n\n`;
        }
      }
    });

    // 在移动设备上，我们可以使用文件系统API保存文件
    // 注意：这需要请求文件系统权限
    const fileName = `聊天记录_${aiObject.value.name}_${new Date()
      .toISOString()
      .slice(0, 10)}.txt`;

    // 检查平台
    if (uni.getSystemInfoSync().platform === "android") {
      // Android平台
      const filePath = `_doc://${fileName}`;
      uni.saveFile({
        tempFilePath: filePath,
        success: (res) => {
          uni.showToast({
            title: "聊天记录已保存",
            icon: "success",
          });
        },
        fail: (err) => {
          console.error("保存文件失败:", err);
          // 备用方案：使用剪贴板
          uni.setClipboardData({
            data: chatText,
            success: () => {
              uni.showToast({
                title: "聊天记录已复制到剪贴板",
                icon: "none",
              });
            },
          });
        },
      });
    } else {
      // iOS或其他平台，使用文件选择器或剪贴板
      uni.setClipboardData({
        data: chatText,
        success: () => {
          uni.showModal({
            title: "导出成功",
            content: "聊天记录已复制到剪贴板，您可以粘贴到其他应用中保存。",
            showCancel: false,
          });
        },
      });
    }
  } catch (error) {
    console.error("导出聊天记录错误:", error);
    uni.showToast({
      title: "导出失败，请重试",
      icon: "none",
    });
  }
};

// 输入框内容
const inputMessage = ref("");
// 滚动位置
const scrollTop = ref(0);

const messageCore = async (msg) => {
  //   const newMessage = {
  //     type: "ai",
  //     content: "",
  //     streamContent: "",
  //     reasoningContent: "",
  //     streamReasoningContent: "",
  //     isStreaming: true,
  //   };
  //   chatList.value.push(newMessage);
  if (msg === "[DONE]") {
    chatList.value[chatList.value.length - 1].isStreaming = false;
    chatList.value[chatList.value.length - 1].content = chatList.value[
      chatList.value.length - 1
    ].streamContent.replace(/^\n+/, "");
    chatList.value[chatList.value.length - 1].reasoningContent = chatList.value[
      chatList.value.length - 1
    ].streamReasoningContent.replace(/^\n+/, "");
    chatList.value = [...chatList.value];
    await nextTick();
    scrollToBottom();
  }
  const data = JSON.parse(msg);
  const content = data.choices[0].delta.content;
  const reasoningContent = data.choices[0].delta.reasoning_content;
  console.log("content", content);
  console.log("reasoningContent", reasoningContent);

  if (content) {
    if (!chatList.value[chatList.value.length - 1].streamContent) {
      chatList.value[chatList.value.length - 1].streamContent = content.replace(
        /^\n+/,
        ""
      );
    } else {
      chatList.value[chatList.value.length - 1].streamContent += content;
    }
  }
  if (reasoningContent) {
    if (!chatList.value[chatList.value.length - 1].streamReasoningContent) {
      chatList.value[chatList.value.length - 1].streamReasoningContent =
        reasoningContent.replace(/^\n+/, "");
    } else {
      chatList.value[chatList.value.length - 1].streamReasoningContent +=
        reasoningContent;
    }
  }
  chatList.value = [...chatList.value];
  await nextTick();
  scrollToBottom();
};
// 处理流式响应
const handleStreamResponse = async (response) => {
  response = JSON.parse(response);
  const newMessage = {
    type: "ai",
    content: "",
    streamContent: "",
    reasoningContent: "",
    streamReasoningContent: "",
    isStreaming: true,
  };
  chatList.value.push(newMessage);

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        newMessage.isStreaming = false;
        newMessage.content = newMessage.streamContent.replace(/^\n+/, "");
        newMessage.reasoningContent = newMessage.streamReasoningContent.replace(
          /^\n+/,
          ""
        );
        chatList.value = [...chatList.value];
        console.log("chatList", chatList.value);
        await nextTick();
        // 保存聊天记录
        saveChatHistory();
        break;
      }

      const chunk = decoder.decode(value, {
        stream: true,
      });
      const lines = chunk.split("\n\n");

      for (const line of lines) {
        if (line.startsWith("data: ")) {
          const data_origin = line.slice(6).trim();
          if (data_origin === "[DONE]") continue;
          try {
            if (data_origin) {
              const data = JSON.parse(data_origin);
              const content = data.choices[0].delta.content;
              const reasoningContent = data.choices[0].delta.reasoning_content;

              if (content) {
                if (!newMessage.streamContent) {
                  newMessage.streamContent = content.replace(/^\n+/, "");
                } else {
                  newMessage.streamContent += content;
                }
              }
              if (reasoningContent) {
                if (!newMessage.streamReasoningContent) {
                  newMessage.streamReasoningContent = reasoningContent.replace(
                    /^\n+/,
                    ""
                  );
                } else {
                  newMessage.streamReasoningContent += reasoningContent;
                }
              }

              chatList.value = [...chatList.value];
              await nextTick();
              scrollToBottom();
            }
          } catch (e) {
            console.error("Error parsing JSON:", e, data_origin);
          }
        }
      }
    }
  } catch (error) {
    console.error("Stream reading error:", error);
    newMessage.isStreaming = false;
    newMessage.content = "读取响应时发生错误";
    chatList.value = [...chatList.value];
    await nextTick();
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return;

  // 添加用户消息
  chatList.value.push({
    type: "user",
    content: inputMessage.value,
  });

  const userInput = inputMessage.value;
  inputMessage.value = "";
  scrollToBottom();

  // 保存聊天记录
  saveChatHistory();

  try {
    // 这里替换为你的实际API端点
    chatSSEClientRef.value.startChat({
      url: API_URL,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: API_KEY.value,
      },
      body: {
        model: "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
        messages: [
          {
            role: "user",
            content: userInput,
          },
        ],
        stream: true,
        max_tokens: 2048,
        temperature: 0.7,
        top_p: 0.7,
        top_k: 50,
        frequency_penalty: 0.5,
      },
    });

    // if (!response.ok) throw new Error("Network response was not ok");
    // await handleStreamResponse(response);
  } catch (error) {
    console.error("Error:", error);
    // 处理错误情况
    chatList.value.push({
      type: "ai",
      content: "抱歉，发生了一些错误，请稍后重试。",
    });
  }
  const newMessage = {
    type: "ai",
    content: "",
    streamContent: "",
    reasoningContent: "",
    streamReasoningContent: "",
    isStreaming: true,
  };
  chatList.value.push(newMessage);
  scrollToBottom();
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    scrollTop.value = 9999999;
  }, 100);
};

// 添加返回方法
const goBack = () => {
  uni.navigateBack();
};

onMounted(() => {
  scrollToBottom();
});

// 解析 Markdown 函数
const parseMarkdown = (content) => {
  if (!content) return "";
  try {
    marked.setOptions({
      breaks: true,
      gfm: true,
    });
    return marked(content);
  } catch (error) {
    console.error("Markdown parsing error:", error);
    return content;
  }
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background-color: #ffffff;
  padding: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: sticky;
  top: 0;
  z-index: 100;
  // padding-top: var(--status-bar-height);
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .back-btn {
    padding: 20rpx;
    margin-right: 10rpx;

    .iconfont {
      font-size: 36rpx;
      color: #333;
    }
  }

  .header-content {
    flex: 1;
    display: flex;
    align-items: center;

    .header-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 30rpx;
      margin-right: 20rpx;
    }

    .header-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .export-btn {
    padding: 20rpx;
    margin-left: 10rpx;
  }
}

.chat-list {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.chat-item {
  margin-bottom: 24rpx;
  display: flex;
  align-items: flex-start;
  padding: 0 20rpx;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    flex-shrink: 0;
  }

  &.chat-right {
    justify-content: flex-end;

    .message-content {
      align-items: flex-end;
      margin-right: 16rpx;
    }
  }

  &.chat-left {
    justify-content: flex-start;

    .message-content {
      margin-left: 16rpx;
    }
  }
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  max-width: 70%;
}

.reasoning-bubble {
  background-color: rgba(25, 137, 250, 0.1);
  padding: 16rpx 20rpx;
  border-radius: 16rpx;
  font-size: 26rpx;
  color: #666;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 4rpx;

  .reasoning-header {
    display: flex;
    align-items: center;
    margin-bottom: 6rpx;

    .reasoning-title {
      margin-left: 8rpx;
      font-size: 24rpx;
      color: #1989fa;
      font-weight: 500;
    }
  }
}

.chat-bubble {
  max-width: 100%;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  word-break: break-all;
  line-height: 1.4;
  box-sizing: border-box;
  white-space: pre-wrap;
}

.user-bubble {
  background-color: #1989fa;
  color: #ffffff;
}

.ai-bubble {
  background-color: #ffffff;
  color: #333333;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.input-area {
  padding: 20rpx;
  background-color: #ffffff;
  border-top: 2rpx solid #eee;
  display: flex;
  align-items: center;
}

.message-input {
  flex: 1;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.send-btn {
  width: 120rpx;
  height: 80rpx;
  background-color: #1989fa;
  color: #ffffff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

// 添加打字机光标动画
.typing-cursor {
  display: inline-block;
  animation: blink 1s infinite;
  font-weight: bold;
  padding-left: 2px;
}

@keyframes blink {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
</style>